package com.fengye.serialization;

import com.fengye.serialization.common.SerializeType;
import com.fengye.serialization.engine.SerializerEngine;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @Author fengye
 * @Date 2023/2/12 11:43
 **/
public class NettyEncodeHandler extends MessageToByteEncoder {

    private SerializeType serializeType;

    public NettyEncodeHandler(SerializeType serializeType) {
        this.serializeType = serializeType;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object in, ByteBuf out) throws Exception {
        // 将对象序列化为字节数组
        byte[] data = SerializerEngine.serialize(in, serializeType.getSerializeType());
        // 将字节数组（消息体）的长度作为消息头写入
        out.writeInt(data.length);
        // 写入序列化后得到的字节数组
        out.writeBytes(data);
    }
}
